package org.an.proj.contacts.ui.contact;

import android.Manifest;
import android.animation.ObjectAnimator;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ListView;
import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import com.tbruyelle.rxpermissions.RxPermissions;
import java.util.ArrayList;
import java.util.List;
import me.drakeet.materialdialog.MaterialDialog;
import org.an.ku.base.BaseFragment;
import org.an.ku.base.itf.OnItemClickListener;
import org.an.ku.util.SimpleTextWatcher;
import org.an.ku.util.StringUtil;
import org.an.ku.util.ToastUtil;
import org.an.ku.view.MyTextView;
import org.an.ku.view.SearchView;
import org.an.ku.view.dialog.chose.ChooseDialog;
import org.an.ku.view.dialog.chose.ChooseDialogInfo;
import org.an.ku.view.indexview.Binder;
import org.an.ku.view.indexview.IndexView;
import org.an.proj.contacts.MyApplication;
import org.an.proj.contacts.R;
import org.an.proj.contacts.adapter.ContactAdapter;
import org.an.proj.contacts.config.LogUtil;
import org.an.proj.contacts.db.DBManager;
import org.an.proj.contacts.db.dao.ContactInfoDao;
import org.an.proj.contacts.db.dao.GroupInfoDao;
import org.an.proj.contacts.eventbus.EventController;
import org.an.proj.contacts.eventbus.EventTag;
import org.an.proj.contacts.model.ContactInfo;
import org.an.proj.contacts.model.GroupInfo;
import org.an.proj.contacts.model.PhoneInfo;
import org.an.proj.contacts.util.ContactsHelper;
import org.an.proj.contacts.util.IntentUtil;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.greenrobot.greendao.query.QueryBuilder;
import rx.functions.Action1;

/**
 * 创建时间：2016年10月13日14:48 <br>
 * 作者：fuchaoyang <br>
 * 描述：联系人Fragment
 */
public class ContactFragment extends BaseFragment
    implements AdapterView.OnItemClickListener, OnItemClickListener<ContactInfo>,
    ChooseDialog.OnSingleItemClickListener, ContactsHelper.IResult<link.model.ContactInfo> {

  @Bind(R.id.tv_title) MyTextView mTvTitle;
  @Bind(R.id.search_view) SearchView mSearchView;
  @Bind(R.id.fl_search) FrameLayout mFlSearch;
  @Bind(R.id.index_view) IndexView mIndexView;
  @Bind(R.id.lv_contact) ListView mLvContact;
  @Bind(R.id.iv_spinner_group) ImageView mIvSpinnerGroup;

  private ContactInfoDao mContactDao;
  private GroupInfoDao mGroupInfoDao;
  private ContactAdapter mAdapter;
  private String mQuery;
  private MaterialDialog mToastDialog;
  private ChooseDialog mGroupChooseDialog;
  // 当前分组，默认为 “全部联系人”
  private long mCurrGroupId = ALL_GROUP_ID;
  private static final long ALL_GROUP_ID = -1L;
  private List<ChooseDialogInfo> mGroupChooseList;
  private ContactsHelper mContactsHelper;

  public ContactFragment() {
    // Required empty public constructor
  }

  public static ContactFragment newInstance() {
    ContactFragment fragment = new ContactFragment();
    //Bundle args = new Bundle();
    //fragment.setArguments(args);
    return fragment;
  }

  @Override public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mContactsHelper = new ContactsHelper(this);
    RxPermissions rxPermissions = new RxPermissions(getActivity());
    // rxPermissions request被允许的话就不用再次申请了
    // 如果拒绝过，下次权限申请的弹窗就会提示（拒绝后不再询问）
    rxPermissions.request(/*Manifest.permission.READ_CALL_LOG, */Manifest.permission.READ_CONTACTS)
        .subscribe(new Action1<Boolean>() {
          @Override public void call(Boolean granted) {
            if (granted) { // Always true pre-M
              // TODO 授予了权限才能做这件事情
              mContactsHelper.loadCallRecord();
            } else {
              // Oups permission denied
              ToastUtil.toast(MyApplication.getInstance(), "权限申请被拒绝");
              //getActivity().finish();
            }
          }
        });
    // 初始化数据放到这里
    mToastDialog = new MaterialDialog(getContext()).setCanceledOnTouchOutside(true);
    mContactDao = DBManager.getDaoSession().getContactInfoDao();
  }

  @Override public View onCreateView(LayoutInflater inflater, ViewGroup container,
      Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View view = inflater.inflate(R.layout.fragment_contact, container, false);
    ButterKnife.bind(this, view);
    init();
    EventController.register(this);
    return view;
  }

  private void init() {
    mSearchView.setTextChangedListener(new SimpleTextWatcher() {
      @Override public void afterTextChanged(String s) {
        mQuery = s;
        queryAndRefresh();
      }
    });
    mAdapter = new ContactAdapter(getContext(), this);
    mLvContact.setAdapter(mAdapter);
    mLvContact.setOnItemClickListener(this);
    queryAndRefresh();
    new Binder(mLvContact, mIndexView) {
      @Override public String getListItemKey(int position) {
        return mAdapter.getItem(position).getName();
      }
    }.bind();
    // 初始化分组dialog
    mGroupChooseDialog = new ChooseDialog(getContext());
    mGroupChooseDialog.bindTextView(mTvTitle).setMaxItemCount(4).setOnSingleItemClickListener(this);
    mGroupChooseDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
      @Override public void onCancel(DialogInterface dialog) {
        spinnerGroup(false);
      }
    });
    onEventRefreshGroup(null);
  }

  private void queryAndRefresh() {
    mAdapter.setDatas(getContacts(mQuery));
  }

  @Override public void onDestroyView() {
    EventController.unregister(this);
    ButterKnife.unbind(this);
    super.onDestroyView();
  }

  /**
   * 搜索，目前数据量小，查询操作直接在UI线程中执行，以后数据量大的话要考虑在子线程中进行
   *
   * @param query 关键词:小猪
   */
  private List<ContactInfo> getContacts(String query) {
    List<ContactInfo> list;
    QueryBuilder<ContactInfo> builder = mContactDao.queryBuilder();
    if (StringUtil.trim(query).length() > 0) {
      // 模糊查询
      builder = builder.whereOr(ContactInfoDao.Properties.Name.like("%" + query + "%"),//包含'小猪'
          ContactInfoDao.Properties.Pinyin.like("%" + query), // xiaozhu
          ContactInfoDao.Properties.Jianpin.like("%" + query)); // xz
    }
    if (mCurrGroupId != -1) {
      // 添加分组
      builder.where(ContactInfoDao.Properties.GroupId.eq(mCurrGroupId));
    }
    // 按index排序
    list = builder.orderAsc(ContactInfoDao.Properties.Index).list();
    // 自己做排序处理
    //Collections.sort(list, new PinyinComparator<ContactInfo>() {
    //  @Override public int compare(ContactInfo t1, ContactInfo t2) {
    //    return compare(t1.getPinyin(), t2.getPinyin());
    //  }
    //});
    return list;
  }

  /**
   * 更新分组信息
   *
   * @param tag tag
   * {@link EventController#postRefreshContactsEvent()}
   */
  @Subscribe(threadMode = ThreadMode.MAIN) public void onEventRefreshGroup(
      EventTag.TagRefreshContacts tag) {
    // 从数据库中重新生成
    if (mGroupInfoDao == null) {
      mGroupInfoDao = DBManager.getDaoSession().getGroupInfoDao();
    }
    List<GroupInfo> groupInfos = mGroupInfoDao.loadAll();
    mGroupChooseList = new ArrayList<>();
    // 添加“全部联系人”
    mGroupChooseList.add(new ChooseDialogInfo(null, mCurrGroupId == ALL_GROUP_ID,
        getString(R.string.str_all_contact), ALL_GROUP_ID));
    for (GroupInfo groupInfo : groupInfos) {
      mGroupChooseList.add(
          new ChooseDialogInfo(null, groupInfo.getId() == mCurrGroupId, groupInfo.getGroupName(),
              groupInfo.getId()));
    }
    // 处理“未分组”
    //mGroupChooseList.add(new ChooseDialogInfo(null, mCurrGroupId == ALL_GROUP_ID,
    //    getString(R.string.str_no_group), ALL_GROUP_ID));
    mGroupChooseDialog.setData(mGroupChooseList);
  }

  @OnClick({ R.id.btn_add, R.id.btn_opensliding, R.id.tv_title, R.id.iv_spinner_group })
  public void onClick(View view) {
    switch (view.getId()) {
      case R.id.btn_add:
        IntentUtil.goToOthers(mContext, ContactDetailActivity.class);
        break;
      case R.id.btn_opensliding:
        EventController.postToggleSlidingEvent(true);
        break;
      case R.id.tv_title:
      case R.id.iv_spinner_group:
        spinnerGroup(true);
        break;
    }
  }

  /**
   * @param isExpand 是否展开
   */
  private void spinnerGroup(boolean isExpand) {
    if (isExpand) {
      ObjectAnimator.ofFloat(mIvSpinnerGroup, "rotationX", 0, 180).setDuration(200).start();
      mGroupChooseDialog.show();
    } else {
      ObjectAnimator.ofFloat(mIvSpinnerGroup, "rotationX", 180, 0).setDuration(200).start();
      //mGroupChooseDialog.dismiss();
    }
  }

  /**
   * 刷新联系人列表
   *
   * @param tag tag
   * {@link EventController#postRefreshContactsEvent()}
   */
  @Subscribe(threadMode = ThreadMode.MAIN) public void onEventRefreshContacts(
      EventTag.TagRefreshContacts tag) {
    queryAndRefresh();
  }

  @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    ContactInfo info = mAdapter.getItem(position);
    mToastDialog.setMessage(info.toString()).show();
  }

  /**
   * @param position 列表下标
   * @param info 列表数据对象
   * @param v view
   */
  @Override public void onItemClick(int position, ContactInfo info, View v) {
    switch (v.getId()) {
      // 这样写其实不好，最好是不要判断id，但是又会写多个接口，发eventbus也可以
      case R.id.iv_avatar:
        // getPhones()会查询数据库
        List<PhoneInfo> phones = info.getPhones();
        mToastDialog.setMessage(phones.toString()).show();
        break;
      case R.id.btn_delete:
        mContactDao.delete(info);
        queryAndRefresh();
        break;
    }
  }

  /**
   * 选择分组
   *
   * @param position 列表下标
   */
  @Override public void onSingleItemClick(ChooseDialog dialog, int position,
      ChooseDialogInfo info) {
    mCurrGroupId = (long) info.value;
    //  刷新列表
    spinnerGroup(false);
    queryAndRefresh();
  }

  @Override public void loadFinished(boolean hasMore, List<link.model.ContactInfo> list) {
    LogUtil.e("contact", list.toString());
  }
}
